﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Models;
using MongoDB.Driver.Linq;
using MongoDB.Driver.Builders;
using MongoDB.Bson;

namespace DatabaseRepository
{
    public class ImageRepository : IImageRepository
    {
        private readonly MongoConnectionHelper<Images> _images;

        public ImageRepository()
        {
            _images = new MongoConnectionHelper<Images>();
        }

        public IEnumerable<Images> GetImagelist() 
        {
            try
            {
                return (from i in _images.Collection.AsQueryable()
                        select i).ToList();
            }
            catch (Exception)
            {
                return new List<Images>();
            }
        }

        public bool SaveImage(string name, string url) 
        {
            try
            {
                _images.Collection.Save(new Images { ImagePath = name, Url = url });
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public string GetUrl(string name) 
        {
            try
            {
                return (from i in _images.Collection.AsQueryable()
                        where i.ImagePath.Equals(name)
                        select i.Url).SingleOrDefault();
            }
            catch (Exception)
            {
                return null;
            }
        }

        public bool DeleteImage(string id) 
        {
            try
            {
                _images.Collection.Remove(Query.EQ("_id", new ObjectId(id)));
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}
